package com.qinker.robot.hook.thread;

import android.support.annotation.NonNull;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Irany 2019/10/22 0022 23:02
 */
public class HookThreadFatory implements ThreadFactory {
    public HookThreadFatory() {
        this("rpcserver-threadpool-" + number.getAndIncrement(), false);
    }

    public HookThreadFatory(String prefix) {
        this(prefix, false);
    }

    public HookThreadFatory(String prefix, boolean daemo) {
        this.prefix = StringUtils.isNotEmpty(prefix) ? prefix + "-thread-" : "";
        daemoThread = daemo;
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
    }

    @Override
    public Thread newThread(@NonNull Runnable r) {
        String name = prefix + number.getAndIncrement();
        Thread ret = new Thread(threadGroup, r, name, 0);
        ret.setDaemon(daemoThread);
        return ret;
    }


    private final String prefix;
    private static final AtomicInteger number = new AtomicInteger(1);
    private final boolean daemoThread;

    private final ThreadGroup threadGroup;
}
